<template>
  <div>
    <!-- 公共导航头 -->
    <CommonHeader/>

    <!-- 聊天主体内容 -->
    <div class="chat-container">
      <!-- 左侧：聊天对象列表 -->
      <div class="chat-sidebar">
        <div class="sidebar-header">
          <h3>消息</h3>
          <n-badge :value="totalUnreadCount" :show="totalUnreadCount > 0">
            <n-icon size="20">
              <MessageCircleIcon/>
            </n-icon>
          </n-badge>
        </div>

        <div class="chat-list">
          <div
              v-for="session in chatSessions"
              :key="session.id"
              class="chat-item"
              :class="{ active: currentSession?.id === session.id }"
              @click="selectSession(session)"
          >            <n-avatar
                :src="session.otherUser?.avatar || '/default_avatar.svg'"
                :fallback-src="'/default_avatar.svg'"
                size="medium"
            />
            <div class="chat-info">
              <div class="chat-name">{{ session.otherUser?.username || '未知用户' }}</div>
              <div class="chat-last-msg">{{ session.lastMessage || '暂无消息' }}</div>
            </div>
            <div class="chat-meta">
              <div class="chat-time">{{ formatTime(session.lastTime) }}</div>
              <n-badge
                  :value="session.unreadCount"
                  :show="session.unreadCount > 0"
                  type="error"
                  size="small"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：聊天窗口 -->
      <div class="chat-main">
        <div v-if="!currentSession" class="chat-empty">
          <n-empty description="请选择一个聊天对象">
            <template #icon>
              <n-icon size="60">
                <MessageCircleIcon/>
              </n-icon>
            </template>
          </n-empty>
        </div>

        <div v-else class="chat-window">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <n-avatar
                :src="currentSession.otherUser?.avatar"
                :fallback-src="'/default_avatar.svg'"
                size="medium"
            />
            <div class="header-info">
              <h4>{{ currentSession.otherUser?.username || '未知用户' }}</h4>
              <span class="online-status" :class="{ online: isUserOnline }">
              {{ isUserOnline ? '在线' : '离线' }}
            </span>
            </div>
          </div>

          <!-- 消息区域 -->
          <div class="message-area" ref="messageArea">
            <div
                v-for="message in currentMessages"
                :key="message.id"
                class="message-item"
                :class="{ 'message-sent': message.fromId === currentUserId }"
            >
              <n-avatar
                  :src="message.fromId === currentUserId ? currentUser?.avatar : currentSession.otherUser?.avatar"
                  :fallback-src="'/default_avatar.svg'"
                  size="small"
              />              <div class="message-content">
                <div class="message-text" v-html="message.content"></div>
                <div class="message-time">{{ formatTime(message.createTime) }}</div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <n-input
                v-model:value="messageInput"
                type="textarea"
                placeholder="请输入消息..."
                :autosize="{ minRows: 1, maxRows: 3 }"
                @keydown.enter.prevent="sendMessage"
            />
            <n-button
                type="primary"
                @click="sendMessage"
                :loading="sending"
                :disabled="!messageInput.trim()"
            >
              发送
            </n-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, computed, nextTick, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {useMessage} from 'naive-ui'
import {ChatbubbleEllipses as MessageCircleIcon} from '@vicons/ionicons5'
import CommonHeader from '../../components/CommonHeader.vue'
import http from '../../utils/http.js'

const router = useRouter()
const route = useRoute()
const message = useMessage()

// 基础配置
const BASE_URL = 'http://localhost:8080'

// 响应式数据
const chatSessions = ref([])
const currentSession = ref(null)
const currentMessages = ref([])
const messageInput = ref('')
const sending = ref(false)
const messageArea = ref(null)
const isUserOnline = ref(false)

// WebSocket连接
let websocket = null

// 当前用户信息
const currentUser = computed(() => {
  try {
    return JSON.parse(localStorage.getItem('user') || '{}')
  } catch {
    return {}
  }
})

const currentUserId = computed(() => currentUser.value.userId)

// 总未读消息数
const totalUnreadCount = computed(() => {
  return chatSessions.value.reduce((total, session) => total + (session.unreadCount || 0), 0)
})

// 初始化
onMounted(async () => {
  if (!currentUserId.value) {
    message.error('请先登录')
    router.push('/login')
    return
  }
  await loadChatSessions()
  initWebSocket()
  
  // 处理从预约跳转过来的聊天会话
  const sessionId = route.query.sessionId
  const type = route.query.type
  const reservationId = route.query.reservationId
  const gymName = route.query.gymName
  const reservationType = route.query.reservationType
  const reservationDate = route.query.reservationDate
  const timeSlot = route.query.timeSlot
  
  // 处理从TradeView跳转过来的聊天会话
  const sellerId = route.query.sellerId
  const sellerName = route.query.sellerName
  const sellerAvatar = route.query.sellerAvatar

  console.log('=== 路由参数检查 ===')
  console.log('sessionId:', sessionId)
  console.log('type:', type)
  console.log('reservationId:', reservationId)
  console.log('sellerId:', sellerId)
  console.log('sellerName:', sellerName)
  console.log('sellerAvatar:', sellerAvatar)
  if (type === 'reservation') {
    // 处理预约相关的聊天会话
    let targetSession = null
    
    if (sessionId) {
      // 如果有具体的会话ID，先尝试查找
      targetSession = chatSessions.value.find(session => 
        session.id === parseInt(sessionId)
      )
    }
    
    if (!targetSession && reservationId && gymName) {
      // 如果没有找到会话或没有会话ID，但有预约信息，创建或查找与场馆管理员的会话
      console.log('没有找到指定会话，尝试查找场馆管理员会话或创建新会话')
      
      // 这里可能需要根据场馆ID查找管理员ID，暂时使用第一个会话或创建新会话
      // 如果聊天列表为空，等待加载完成后再处理
      if (chatSessions.value.length === 0) {
        console.log('聊天列表为空，等待加载...')
        // 等待一下聊天列表加载
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
      
      // 选择第一个会话作为临时解决方案，或者可以根据场馆信息查找特定的管理员
      if (chatSessions.value.length > 0) {
        targetSession = chatSessions.value[0]
        console.log('使用第一个可用会话:', targetSession)
      }
    }
    
    if (targetSession) {
      console.log('找到预约相关的聊天会话，直接选择')
      await selectSession(targetSession)
      
      // 自动发送预约信息消息
      if (reservationId && gymName) {
        const reservationMessage = `您好！我刚刚提交了一个${reservationType}申请：\n\n📍 场馆：${gymName}\n📅 日期：${reservationDate}\n⏰ 时间：${timeSlot}\n\n请确认我的预约，谢谢！`
        
        console.log('准备发送预约消息:', reservationMessage)
        
        // 确保WebSocket连接建立后再发送消息
        try {
          await waitForWebSocketConnection()
          messageInput.value = reservationMessage
          await sendMessageWithRetry()
        } catch (error) {
          console.error('发送预约消息失败:', error)
          message.error('自动发送预约信息失败，请手动发送')
        }
      }
    } else {
      console.log('未找到可用的聊天会话')
      message.warning('未找到可用的聊天会话，请手动联系场馆管理员')
    }
  }else if (sellerId) {
    // 查找对应的聊天会话
    const targetSession = chatSessions.value.find(session =>
        session.id === parseInt(sessionId) ||
        session.otherUser?.userId === parseInt(sellerId)
    )

    if (targetSession) {
      console.log('找到已存在的会话，直接选择')
      await selectSession(targetSession)
    } else {
      // 如果会话不存在，创建新会话
      console.log('会话不存在，创建新会话')
      const userInfo = {
        userId: parseInt(sellerId),
        username: sellerName || '未知用户',
        avatar: sellerAvatar || '/default_avatar.svg'
      }
      console.log('准备调用startChatWithUser，参数:', userInfo)
      await startChatWithUser(userInfo)
    }
  } else {
    // 如果URL中有targetUserId参数，自动开始聊天
    const targetUserId = route.query.targetUserId
    if (targetUserId) {
      await startChatWith(parseInt(targetUserId))
    }
  }
})

onUnmounted(() => {
  if (websocket) {
    websocket.close()
  }
})

// 监听当前会话变化，加载聊天记录
watch(currentSession, async (newSession) => {
  if (newSession) {
    await loadChatHistory(newSession)
    // 标记消息为已读
    await markAsRead(newSession.otherUser.userId)
    // 更新未读数
    newSession.unreadCount = 0
  }
})

// 测试WebSocket连接信息
const testWebSocketConnection = async () => {
  try {
    const response = await http.get('/v1/chat/test-websocket')
    if (response.data.code === 2000) {
      console.log('WebSocket服务器信息:', response.data.data)
      return response.data.data
    }
  } catch (error) {
    console.error('无法获取WebSocket服务器信息:', error)
    return null
  }
}

// 初始化WebSocket
const initWebSocket = async () => {
  const user = currentUser.value
  console.log('当前用户信息:', user)
  if (!user || !user.tokenInfo || !user.tokenInfo.isLogin) {
    console.error('用户未登录，无法建立WebSocket连接')
    return
  }

  // 先测试WebSocket服务器信息
  const serverInfo = await testWebSocketConnection()
  if (!serverInfo) {
    console.error('WebSocket服务器测试失败')
    message.error('WebSocket服务器连接测试失败')
    return
  }

  // 构建Spring WebSocket URL，包含token参数
  const wsUrl = `ws://localhost:8080/websocket/chat/${currentUserId.value}?token=${user.tokenInfo.tokenValue}`
  console.log('尝试连接Spring WebSocket聊天:', wsUrl)
  console.log('用户ID:', currentUserId.value)
  console.log('Token长度:', user.tokenInfo.tokenValue?.length)
  console.log('服务器信息:', serverInfo)
  
  try {
    websocket = new WebSocket(wsUrl)
    
    websocket.onopen = () => {
      console.log('Spring WebSocket聊天连接成功')
      isUserOnline.value = true
      message.success('Spring WebSocket聊天连接成功')
    }
    
    websocket.onmessage = async (event) => {
    try {
      console.log('收到WebSocket消息:', event.data)
      const data = JSON.parse(event.data)

      if (data.type === 'connect') {
        // 连接成功消息
        console.log('WebSocket连接确认:', data.message)
        return
      }
      
      if (data.type === 'ack') {
        // 消息发送确认
        console.log('消息发送成功:', data.messageId)
        return
      }
        // 收到新的聊天消息
      if (data.messageId || data.content) {
        console.log('收到新聊天消息:', data)
        console.log('当前会话信息:', currentSession.value)
        console.log('当前用户ID:', currentUserId.value)
        console.log('消息发送者ID:', data.fromId)
        console.log('消息接收者ID:', data.toId)

        // 修复消息判断逻辑：检查消息是否与当前会话相关
        // 消息与当前会话相关的条件：
        // 1. 消息来自当前会话的对方用户（data.fromId === otherUser.userId）
        // 2. 消息发给当前会话的对方用户（data.toId === otherUser.userId）
        // 3. 消息发给当前用户自己（data.toId === currentUserId.value）
        if (currentSession.value &&
            ((data.fromId === currentSession.value.otherUser.userId && data.toId === currentUserId.value) || 
             (data.fromId === currentUserId.value && data.toId === currentSession.value.otherUser.userId))) {
          
          console.log('消息属于当前会话，准备显示')
          
          // 检查消息是否已存在（避免重复）
          const exists = currentMessages.value.some(msg => 
            msg.messageId === data.messageId || 
            (msg.content === data.content && msg.fromId === data.fromId && 
             Math.abs(new Date(msg.createTime) - new Date(data.createTime)) < 1000)
          )
          
          console.log('消息是否已存在:', exists)
          
          if (!exists) {
            console.log('添加新消息到当前会话')
            currentMessages.value.push(data)
            nextTick(scrollToBottom)
          } else {
            console.log('消息已存在，跳过添加')
          }
          
          // 如果是别人发来的消息，标记为已读
          if (data.fromId === currentSession.value.otherUser.userId) {
            console.log('标记来自对方的消息为已读')
            await markAsRead(data.fromId)
          }
        } else {
          console.log('消息不属于当前会话，更新会话列表')
          // 更新会话列表
          await loadChatSessions()
        }
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
      console.error('原始消息:', event.data)
    }
  }
  websocket.onclose = (event) => {
    console.log('WebSocket连接关闭')
    console.log('关闭代码:', event.code)
    console.log('关闭原因:', event.reason)
    console.log('是否为干净关闭:', event.wasClean)
    isUserOnline.value = false
    
    // 根据关闭代码显示不同的错误消息
    if (event.code === 1006) {
      message.error('WebSocket连接异常关闭，可能是网络问题')
    } else if (event.code === 1003) {
      message.error('WebSocket协议错误')
    } else if (event.code !== 1000) {
      message.error(`WebSocket连接关闭，代码: ${event.code}`)
    }
    
    // 尝试重连
    setTimeout(() => {
      if (currentUserId.value && currentUser.value.tokenInfo?.isLogin) {
        console.log('尝试重新连接WebSocket...')
        initWebSocket()
      }
    }, 3000)
  }
  
  websocket.onerror = (error) => {
    console.error('WebSocket连接错误:', error)
    console.error('WebSocket状态:', websocket?.readyState)
    console.error('WebSocket URL:', wsUrl)
    isUserOnline.value = false
    message.error('WebSocket连接失败，请检查网络或联系管理员')
  }
  
  } catch (error) {
    console.error('创建WebSocket连接失败:', error)
    message.error('创建WebSocket连接失败: ' + error.message)
  }
}

// 加载聊天会话列表
const loadChatSessions = async () => {
  try {
    const response = await http.get(`/v1/chat/sessions`)

    if (response.data.code === 2000) {
      // 处理会话数据，添加其他用户信息和未读数
      chatSessions.value = await Promise.all(
          response.data.data.map(async (session) => {
            const otherUserId = session.user1Id === currentUserId.value ? session.user2Id : session.user1Id
            const unreadCount = session.user1Id === currentUserId.value ? session.user1Unread : session.user2Unread

            // 获取其他用户信息
            const otherUser = await getUserInfo(otherUserId)

            // 获取最后一条消息内容
            const lastMessage = await getLastMessageContent(session.lastMsgId)

            return {
              ...session,
              otherUser,
              unreadCount,
              lastMessage
            }
          })
      )
    }
  } catch (error) {
    console.error('加载聊天会话失败:', error)
  }
}

// 获取用户信息
const getUserInfo = async (userId) => {
  try {
    const response = await http.get(`/v1/user/selectByUserId`, {
      params: {userId}
    })

    if (response.data.code === 2000) {
      return response.data.data
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
  return {userId, username: '未知用户'}
}

// 获取最后一条消息内容
const getLastMessageContent = async (messageId) => {
  if (!messageId) return '暂无消息'

  try {
    // 这里可以调用API获取具体消息内容，暂时返回默认值
    return '最新消息...'
  } catch (error) {
    return '暂无消息'
  }
}

// 选择会话
const selectSession = (session) => {
  currentSession.value = session
}

// 开始与指定用户聊天
const startChatWith = async (targetUserId) => {
  // 查找是否已有会话
  let session = chatSessions.value.find(s => s.otherUser.userId === targetUserId)

  if (!session) {
    // 创建新会话
    const otherUser = await getUserInfo(targetUserId)
    session = {
      id: `new_${targetUserId}`,
      user1Id: Math.min(currentUserId.value, targetUserId),
      user2Id: Math.max(currentUserId.value, targetUserId),
      otherUser,
      unreadCount: 0,
      lastMessage: '开始聊天吧...',
      lastTime: new Date()
    }

    chatSessions.value.unshift(session)
  }

  currentSession.value = session
}

// 开始与指定用户聊天（带用户信息）
const startChatWithUser = async (userInfo) => {
  console.log('=== startChatWithUser 被调用 ===')
  console.log('启动与用户的聊天:', userInfo)

  try {
    console.log('=== 准备调用后端 /v1/chat/create API ===')
    // 先尝试调用后端API创建或获取聊天会话
    const requestData = {
      sellerId: userInfo.userId,
      sellerName: userInfo.username,
      equipmentId: null, // 可以为空
      equipmentTitle: '商品咨询' // 默认设备标题
    }
    console.log('发送请求数据:', requestData)
    
    const response = await http.post('/v1/chat/create', requestData)
    console.log('后端响应:', response)

    if (response.data.code === 2000) {
      console.log('=== 会话创建成功，重新加载会话列表 ===')
      // 重新加载聊天会话列表
      await loadChatSessions()
      
      // 查找刚创建的会话
      const newSession = chatSessions.value.find(s => s.otherUser.userId === userInfo.userId)
      
      if (newSession) {
        await selectSession(newSession)
        return
      }
    } else {
      console.error('后端返回错误:', response.data)
    }
  } catch (error) {
    console.error('=== 创建聊天会话失败 ===', error)
  }

  // 如果后端创建失败，使用前端临时会话（向后兼容）
  let session = chatSessions.value.find(s => s.otherUser.userId === userInfo.userId)

  if (!session) {
    // 创建新会话，使用传入的用户信息
    session = {
      id: `new_${userInfo.userId}`,
      user1Id: Math.min(currentUserId.value, userInfo.userId),
      user2Id: Math.max(currentUserId.value, userInfo.userId),
      otherUser: userInfo,
      unreadCount: 0,
      lastMessage: '开始聊天吧...',
      lastTime: new Date()
    }

    chatSessions.value.unshift(session)
  }

  currentSession.value = session
}

// 加载聊天记录
const loadChatHistory = async (session) => {
  try {
    const response = await http.get(`/v1/chat/history`, {
      params: {
        userId: currentUserId.value,
        otherUserId: session.otherUser.userId,
        limit: 50
      }
    })

    if (response.data.code === 2000) {
      currentMessages.value = response.data.data.reverse() // 按时间正序排列
      nextTick(scrollToBottom)
    }
  } catch (error) {
    console.error('加载聊天记录失败:', error)
  }
}

// 等待WebSocket连接建立
const waitForWebSocketConnection = () => {
  return new Promise((resolve, reject) => {
    const maxAttempts = 20 // 最多等待10秒
    let attempts = 0
    
    const checkConnection = () => {
      attempts++
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        console.log('WebSocket连接已建立，可以发送消息')
        resolve()
      } else if (attempts >= maxAttempts) {
        console.error('等待WebSocket连接超时')
        reject(new Error('WebSocket连接超时'))
      } else {
        console.log(`等待WebSocket连接... 尝试 ${attempts}/${maxAttempts}`)
        setTimeout(checkConnection, 500)
      }
    }
    
    checkConnection()
  })
}

// 带重试的发送消息函数
const sendMessageWithRetry = async (maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      console.log(`尝试发送消息，第 ${i + 1} 次`)
      if (!messageInput.value.trim()) {
        console.log('消息内容为空')
        return false
      }
      
      if (!currentSession.value) {
        console.log('没有选择会话')
        return false
      }

      if (!websocket || websocket.readyState !== WebSocket.OPEN) {
        console.log('WebSocket未连接，等待连接...')
        await waitForWebSocketConnection()
      }

      const content = messageInput.value.trim()
      const messageData = {
        toId: currentSession.value.otherUser.userId,
        content: content
      }

      console.log('发送消息数据:', messageData)
      console.log('当前会话:', currentSession.value)
      websocket.send(JSON.stringify(messageData))
      
      // 立即显示发送的消息（乐观更新）
      const tempMessage = {
        messageId: 'temp_' + Date.now(),
        fromId: currentUserId.value,
        toId: currentSession.value.otherUser.userId,
        content: content,
        createTime: new Date().toISOString(),
        readStatus: 0
      }

      currentMessages.value.push(tempMessage)
      messageInput.value = ''
      nextTick(scrollToBottom)
        console.log('消息发送成功')
      message.success('预约信息已发送给场馆管理员')
      return true
      
    } catch (error) {
      console.error(`第 ${i + 1} 次发送消息失败:`, error)
      if (i === maxRetries - 1) {
        message.error('发送预约信息失败，请手动发送')
        return false
      }
      // 等待一秒后重试
      await new Promise(resolve => setTimeout(resolve, 1000))
    }
  }
  return false
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim() || !currentSession.value || sending.value) {
    return
  }

  if (!websocket || websocket.readyState !== WebSocket.OPEN) {
    console.error('WebSocket连接检查失败')
    message.error('WebSocket连接已断开，请稍后重试')
    // 尝试重新连接
    initWebSocket()
    return
  }

  sending.value = true
  const content = messageInput.value.trim()

  const messageData = {
    toId: currentSession.value.otherUser.userId,
    content: content
  }

  try {
    console.log('准备发送消息:', messageData)
    // 发送WebSocket消息
    websocket.send(JSON.stringify(messageData))
    
    // 立即显示发送的消息（乐观更新）
    const tempMessage = {
      messageId: 'temp_' + Date.now(),
      fromId: currentUserId.value,
      toId: currentSession.value.otherUser.userId,
      content: content,
      createTime: new Date().toISOString(),
      readStatus: 0
    }

    currentMessages.value.push(tempMessage)
    messageInput.value = ''
    nextTick(scrollToBottom)
    
    console.log('消息已发送并添加到界面:', tempMessage)
  } catch (error) {
    console.error('发送消息失败:', error)
    message.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 标记消息为已读
const markAsRead = async (fromId) => {
  try {
    await http.post(`/v1/chat/read`, null, {
      params: {
        fromId: fromId,
        toId: currentUserId.value
      }
    })
  } catch (error) {
    console.error('标记消息已读失败:', error)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageArea.value) {
    messageArea.value.scrollTop = messageArea.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''

  const date = new Date(time)
  const now = new Date()
  const diffTime = now - date
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'})
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 暴露给外部使用的方法
defineExpose({
  startChatWith,
  startChatWithUser
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 120px); /* 调整高度以适应CommonHeader */
  background: #f5f5f5;
}

.chat-sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f8f9fa;
}

.chat-item.active {
  background-color: #e3f2fd;
}

.chat-info {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.chat-name {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}

.chat-last-msg {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.chat-time {
  font-size: 11px;
  color: #999;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-info h4 {
  margin: 0;
  font-size: 16px;
}

.online-status {
  font-size: 12px;
  color: #999;
}

.online-status.online {
  color: #52c41a;
}

.message-area {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.message-item.message-sent {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 60%;
}

.message-sent .message-content {
  text-align: right;
}

.message-text {
  background: #f0f0f0;
  padding: 8px 12px;
  border-radius: 12px;
  word-wrap: break-word;
}

.message-sent .message-text {
  background: #1890ff;
  color: white;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-area .n-input {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-sidebar {
    width: 100%;
    position: absolute;
    z-index: 10;
    height: 100%;
  }

  .chat-main {
    width: 100%;
  }

  .message-content {
    max-width: 80%;
  }
}
</style>
